package controller

import (
	"github.com/gin-gonic/gin"
	"guliedu/model"
	"net/http"
	"strconv"
)

type chapterInfo struct {
	CourseID string `json:"courseId"`
	Title    string `json:"title"`
	Sort     int    `json:"sort"`
}

type updateChapterInfo struct {
	ID       int    `json:"id"`
	CourseID string `json:"course_id"`
	Title    string `json:"title"`
	Sort     int    `json:"sort"`
}

func GetChapterInfo(ctx *gin.Context) {
	id := ctx.Param("id")
	chapter, _ := eduChapterService.Select(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": chapter,
	})
	return
}

func AddChapter(ctx *gin.Context) {
	chapter := &chapterInfo{}
	ctx.ShouldBind(&chapter)
	id, _ := strconv.Atoi(chapter.CourseID)

	c := &model.EduChapter{
		CourseID: id,
		Title:    chapter.Title,
		Sort:     chapter.Sort,
	}
	eduChapterService.Insert(c)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func GetChapterVideo(ctx *gin.Context) {
	courseID := ctx.Param("courseID")
	chapterVideos, _ := eduChapterService.GetAllChapterVideo(courseID)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": chapterVideos,
	})
	return
}

func UpdateChapter(ctx *gin.Context) {
	chapter := &updateChapterInfo{}
	ctx.ShouldBind(&chapter)

	id := strconv.Itoa(chapter.ID)
	c, _ := eduChapterService.Select(id)
	c.Title = chapter.Title
	c.Sort = chapter.Sort
	eduChapterService.Update(c)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func DeleteChapter(ctx *gin.Context) {
	id := ctx.Param("id")

	videos, _ := eduVideoService.SelectByChapterID(id)
	if len(videos) > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  "请先删除视频！",
		})
		return
	}

	eduChapterService.Delete(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}
